<template>

  <div class="common-layout">

    <el-container>
      <!-- <el-header >

      </el-header> -->
      <el-main>
        <el-card style="max-width: 1200px;background-color: #f9fafa;text-align: center;">
          <form @submit.prevent="sendMessage">
            <el-input v-model="formData.prompt" :rows="5" style="font-size: 20px;" type="textarea"
                      @keydown="handleKeyDown($event)" placeholder="请输入问题"/>

            <div style="background-color: #66b0e2; ">
              <el-button class="myButton" :loading="isSending" style="" @click="sendMessage">查询</el-button>
              <el-button class="myButton" @click="clearInput">清空</el-button>
              <el-button class="myButton" style="" @click="getLocalIp">本地ip</el-button>
              <el-button class="myButton" style="" @click="resetHistory">重置历史记录</el-button>
            </div>


          </form>
        </el-card>


        <el-card style="max-width: 1200px;background-color: #f9fafa;">
          <template #header>
            <div class="card-header">
              <h3>答案:</h3>
            </div>
          </template>
          <MdPreview style="background-color: #f4f4f6;" theme="github" :modelValue="formattedResponse.value"/>

        </el-card>

      </el-main>
      <!-- <el-footer>Footer</el-footer> -->
      <!-- <template #footer>Footer content</template> -->
    </el-container>
  </div>


</template>


<script setup>
import {computed, onMounted, ref} from 'vue'
import {MdPreview} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import {resetChatHistory, submitForm} from '../js/Chat.ts'

var enableProxy = false

const markdown = ref('');
const responseText = ref('');
const formattedResponse = ref('');
const isSending = ref(false)

var apiUrl = "http://13.48.5.33:8080"
if (enableProxy) {
  apiUrl = "/api"
}


defineProps({
  msg: String
})

const formData = ref({
  prompt: '',
  email: ''
});


onMounted(() => {
  console.log("组件挂载完成")
})

// 用户进入 utools
window.utools.onPluginEnter(({code, type, payload, option}) => {
  // 获取utools的输入文本
  console.log('用户进入插件应用', code, type, payload)
  formData.value.prompt = payload
  console.log("调用接口")
  sendMessage()
})

function clearInput() {
  formData.value.prompt = ''
}

function sendMessage() {
  isSending.value = true;
  console.log(isSending)
  const url = apiUrl + '/chat/chatai'

  submitForm(formData.value.prompt, formData.value.email, url).then((result) => {
    console.log(result); // 输出：Hello, TypeScript!
    responseText.value = result.data.message
    isSending.value = false
  }).catch((error) => {
    console.error(error); // 输出：Error: Failed to get the result.
    isSending.value = false
  });

  formattedResponse.value = computed(
      // 替换换行符为 <br> 标签
      () => {
        // return markdown.value.replace(/\\n/g, '<br>');
        return responseText.value.replace(/\\n/g, '\n')
            .replace(/\\"/g, '"')
            // .replace(/```\n/g, '\n```\n')
            .trim()
      }
  );

}

function getLocalIp() {
  formData.value.prompt = '10.54.21.143'
}


function handleKeyDown(event) {
  if (event.key === 'Enter') {
    if (event.ctrlKey) {
      // 如果按下 Ctrl + Enter，发送消息
      sendMessage();
      event.preventDefault();
    } else {
      // 如果只按下 Enter，插入换行
      formData.value.prompt = formData.value.prompt + '\n'
      event.preventDefault();
    }
  }
}


function resetHistory() {


  const url = apiUrl + '/chat/reset'

  resetChatHistory(url).then((result) => {
    window.confirm("重置记录成功");
    console.log(result); // 输出：Hello, TypeScript!
  }).catch((error) => {
    window.confirm("重置记录失败");
    console.error(error); // 输出：Error: Failed to get the result.
  });
}

</script>

<style scoped>
/* a {
  color: #42b983;
} */

.myButton {
  width: 150px;
  height: 40px;
  font-weight: bolder;
  margin-top: 20px;
  margin-bottom: 20px;
  /* margin-left: 500px; */
}
</style>